﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using cklib;
using Silmoon.Threading;
using System.Net;
using System.Diagnostics;
using System.Collections.Specialized;
using Cooky.Client.RecordDir;
using Silmoon.Windows.Controls.Extension;

namespace Cooky.Client.RecordDir
{
    public partial class RecordListForm : Silmoon.Windows.Forms.GenieForm
    {
        public cklib.CookyDNSAPI cooky = null;
        public Domain[] domainsCache = null;
        public Record[] recordsCache = null;
        public string CurrentDomain = null;
        public int CurrentDomainID = 0;

        public RecordListForm()
        {
            InitializeComponent();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            panel1.Visible = false;
            base.OnFormClosing(e);
        }
        void hideThis()
        {
            panel1.Visible = false;
            HideEx();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            refreshList();
        }

        private void ctlExitButton_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void ctlRefreshButton_Click(object sender, EventArgs e) 
        {
            refreshList();
        }

        void refreshList()
        {
            ctlRecordListView.Columns[4].Text = "MX优先级";
            ctlRefreshButton.Enabled = false;
            ctlModifyRecordButton.Enabled = false;
            ctlEnableButton.Enabled = false;
            ctlDisableButton.Enabled = false;
            ctlDeleteButton.Enabled = false;

            刷新RToolStripMenuItem.Enabled = false;
            编辑EToolStripMenuItem.Enabled = false;
            启用SToolStripMenuItem.Enabled = false;
            禁用DToolStripMenuItem.Enabled = false;
            删除DToolStripMenuItem.Enabled = false;

            Threads.ExecAsync(delegate()
            {
                RecordsResult result = cooky.GetRecords(CurrentDomain);
                this.Invoke(new EventHandler(delegate(object sender, EventArgs args)
                {
                    if (!result.Success) MessageBox.Show("错误：" + result.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                    {
                        recordsCache = result.Records;
                        ctlRecordListView.BeginUpdate();
                        ctlRecordListView.Items.Clear();
                        foreach (Record record in recordsCache)
                        {
                            ListViewItem item = new ListViewItem(new string[] { record.Subname, CookyDNSAPI.RecordTypeToString(record.Type), cooky.AllServerNetmarks[record.Netmark], record.Value, record.MXLevel.ToString(), record.TTL.ToString(), record.ID.ToString() });
                            if (record.State != "ok") item.ForeColor = Color.Silver;
                            ctlRecordListView.Items.Add(item);
                        }
                        ctlRecordListView.EndUpdate();
                        ctlRecordListView.Sort();
                    }
                    ctlRefreshButton.Enabled = true;
                    刷新RToolStripMenuItem.Enabled = true;
                }));
            });
        }
        void modifyDomain()
        {
            string host = ctlRecordListView.SelectedItems[0].Text;
            string recordid = ctlRecordListView.SelectedItems[0].SubItems[6].Text;

            hideThis();
            RecordForm recordForm = new RecordForm();
            recordForm.DomainID = CurrentDomainID;
            recordForm.Domain = CurrentDomain;
            recordForm.RecordID = recordid;
            recordForm.Host = host;
            recordForm.RecordsCache = recordsCache;
            recordForm.DomainsCache = domainsCache;
            recordForm.cooky = cooky;

            recordForm.FormClosed += new FormClosedEventHandler(Form_FormClosed);
            recordForm.ShowEx();
        }
        void addDomain()
        {
            hideThis();
            RecordForm recordForm = new RecordForm();
            recordForm.DomainID = CurrentDomainID;
            recordForm.Domain = CurrentDomain;
            recordForm.RecordID = null;
            recordForm.Host = "";
            recordForm.RecordsCache = recordsCache;
            recordForm.DomainsCache = domainsCache;
            recordForm.cooky = cooky;

            recordForm.FormClosed += new FormClosedEventHandler(Form_FormClosed);
            recordForm.ShowEx();
        }
        void deleteDomain()
        {
            if (MessageBox.Show("确定删除" + ctlRecordListView.SelectedItems[0].Text + "？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (ctlRecordListView.SelectedItems.Count == 0) return;
                string recordid = ctlRecordListView.SelectedItems[0].SubItems[6].Text;
                Threads.ExecAsync(delegate()
                {
                    cooky.RemoveRecord(recordid);
                    this.Invoke(new tmpHander(delegate()
                    {
                        refreshList();
                    }));
                }, null);
            }
        }
        void disableDomain()
        {
            if (MessageBox.Show("确定禁用" + ctlRecordListView.SelectedItems[0].Text + "？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (ctlRecordListView.SelectedItems.Count == 0) return;
                string recordid = ctlRecordListView.SelectedItems[0].SubItems[6].Text;
                Threads.ExecAsync(delegate()
                {
                    cooky.SetRecordState(recordid, false);
                    this.Invoke(new tmpHander(delegate()
                    {
                        refreshList();
                    }));
                }, null);
            }
        }
        void enableDomain()
        {
            if (MessageBox.Show("确定启用" + ctlRecordListView.SelectedItems[0].Text + "？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (ctlRecordListView.SelectedItems.Count == 0) return;
                string recordid = ctlRecordListView.SelectedItems[0].SubItems[6].Text;
                Threads.ExecAsync(delegate()
                {
                    cooky.SetRecordState(recordid, true);
                    this.Invoke(new tmpHander(delegate()
                    {
                        refreshList();
                    }));
                }, null);
            }
        }

        void Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            RecordForm recordForm = sender as RecordForm;

            if (!this.Visible)
            {
                panel1.Visible = true;
                this.ShowEx();
            }
            if (recordForm.SubmitState) refreshList();
        }

        private void ctlModifyRecordButton_Click(object sender, EventArgs e)
        {
            modifyDomain();
        }
        private void ctlRecordListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ctlRecordListView.SelectedItems.Count == 0)
            {
                ctlModifyRecordButton.Enabled = false;
                ctlEnableButton.Enabled = false;
                ctlDisableButton.Enabled = false;
                ctlDeleteButton.Enabled = false;

                编辑EToolStripMenuItem.Enabled = false;
                启用SToolStripMenuItem.Enabled = false;
                禁用DToolStripMenuItem.Enabled = false;
                删除DToolStripMenuItem.Enabled = false;
            }
            else
            {
                ctlModifyRecordButton.Enabled = true;
                ctlEnableButton.Enabled = true;
                ctlDisableButton.Enabled = true;
                ctlDeleteButton.Enabled = true;

                编辑EToolStripMenuItem.Enabled = true;
                启用SToolStripMenuItem.Enabled = true;
                禁用DToolStripMenuItem.Enabled = true;
                删除DToolStripMenuItem.Enabled = true;
            }
        }

        private void ctlRecordListView_DoubleClick(object sender, EventArgs e)
        {
            if (ctlRecordListView.SelectedItems.Count != 0) modifyDomain();
        }
        private void ctlAddRecordButton_Click(object sender, EventArgs e)
        {
            addDomain();
        }
        private void ctlDeleteButton_Click(object sender, EventArgs e)
        {
            //HideEx();
            deleteDomain();
        }
        private void ctlDisableButton_Click(object sender, EventArgs e)
        {
            disableDomain();
        }
        private void ctlEnableButton_Click(object sender, EventArgs e)
        {
            enableDomain();
        }

        private void 网站访问WToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Threads.ExecAsync(thCheck);
        }

        void thCheck()
        {
            try
            {
                ctlRecordListView.Columns[4].Text = "检测结果";

                foreach (ListViewItem item in ctlRecordListView.Items)
                {
                    item.SubItems[4].Text = "解析中...";

                    string host = item.Text + "." + CurrentDomain;
                    string value = item.SubItems[3].Text;
                    if (value.Substring(value.Length - 1, 1) == ".") value = value.Remove(value.Length - 1, 1);

                    host = host.Replace("@.", "");
                    if (host.Contains("*"))
                    {
                        item.ForeColor = Color.Gray;
                        item.SubItems[4].Text = "不支持泛域";
                        continue;
                    }
                    IPAddress ip = null;
                    try
                    {
                        if (CookyDNSAPI.StringToRecordType(item.SubItems[1].Text) == DNS_TYPE.TYPE_A)
                            ip = IPAddress.Parse(value);
                        else ip = Dns.GetHostAddresses(host)[0];
                    }
                    catch
                    {
                        item.ForeColor = Color.Red;
                        item.SubItems[4].Text = "无法解析";
                        continue;
                    }
                    item.SubItems[4].Text = "连接中...";

                    SimpleAsyncWatcher w = new SimpleAsyncWatcher(item.SubItems[6].Text);
                    w.WatchCompleteAsync += new objHandler(w_WatchCompleteAsync);
                    w.StartCheck(ip, 80, host);
                }
            }
            catch { }
        }
        private void 访问VToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string host = ctlRecordListView.SelectedItems[0].Text + "." + CurrentDomain;
            Process.Start(host);
        }

        void w_WatchCompleteAsync(object obj)
        {
            object[] obj1 = (object[])obj;
            bool success = (bool)obj1[0];
            int statuscode = (int)obj1[1];
            string id = (string)obj1[2];
            Stopwatch sw = (Stopwatch)obj1[3];
            if (this.IsDisposed) return;
            this.Invoke(new tmpHander(delegate()
            {
                ctlRecordListView.BeginUpdate();
                foreach (ListViewItem item in ctlRecordListView.Items)
                {
                    if (item.SubItems[6].Text == id.ToString())
                    {
                        if (success)
                        {
                            if (statuscode == 200)
                            {
                                item.SubItems[4].Text = "正常 " + sw.ElapsedMilliseconds + "毫秒";
                                item.BackColor = Color.FromArgb(0xD6, 0xFF, 0xD4);
                            }
                            else if (statuscode > 299 && statuscode < 400)
                            {
                                item.SubItems[4].Text = statuscode + "转跳";
                                item.BackColor = Color.FromArgb(0xD7, 0xF0, 0xFF);
                            }
                            else
                            {
                                item.SubItems[4].Text = statuscode + " 错误";
                                item.BackColor = Color.FromArgb(0xFF, 0xFD, 0xE9);
                            }
                        }
                        else
                        {
                            item.SubItems[4].Text = "无法连接";
                            item.BackColor = Color.FromArgb(0xFF, 0xE6, 0xEF);
                        }
                    }
                }
                ctlRecordListView.EndUpdate();
            }));
        }

        private void ctlContextMenu_Opening(object sender, CancelEventArgs e)
        {
            if (ctlRecordListView.SelectedItems.Count == 0)
            {
                访问VToolStripMenuItem.Enabled = false;
            }
            else
            {
                访问VToolStripMenuItem.Enabled = true;
            }
        }

        private void 刷新RToolStripMenuItem_Click(object sender, EventArgs e)
        {
            refreshList();
        }
        private void 编辑EToolStripMenuItem_Click(object sender, EventArgs e)
        {
            modifyDomain();
        }
        private void 删除DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            deleteDomain();
        }
        private void 添加AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addDomain();
        }
        private void 禁用DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            disableDomain();
        }
        private void 启用SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            enableDomain();
        }

        private void 检测CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Threads.ExecAsync(thCheck, null);
        }

        private void RecordListForm_Shown(object sender, EventArgs e)
        {
            FormGenieExtension.ShowControl(ctlAddRecordButton, true, 0);
            FormGenieExtension.ShowControl(ctlRefreshButton, true, 200);
            FormGenieExtension.ShowControl(ctlModifyRecordButton, true, 400);
            FormGenieExtension.ShowControl(ctlDeleteButton, true, 600);
            FormGenieExtension.ShowControl(ctlDisableButton, true, 800);
            FormGenieExtension.ShowControl(ctlEnableButton, true, 1000);
            FormGenieExtension.ShowControl(ctlExitButton, true, 1200);
        }
    }
}